﻿using MahApps.Metro.Controls.Dialogs;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;

namespace ScriptManager
{
    /// <summary>
    /// login.xaml 的交互逻辑
    /// </summary>
    public partial class login
    {
        
        private MainWindow mw;
        public login(MainWindow mainWindow)
        {
            InitializeComponent();
            mw = mainWindow;
        }

        private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //关闭mw
            if(mw.user_Key == "")
            {
                mw.Close();
            }
        }

        private void login_btn_Click(object sender, RoutedEventArgs e)
        {
            //登录按钮 
            //测试 模拟登录成功
            //this.Close();
            functionFactory ff = new functionFactory();
            WebRequest req = WebRequest.Create($"http://warframe.md4.cn:8081/warframeservice/warframeluaSerivce/login?username={login_user.Text}&password={ff.getMD5(login_pwd.Password)}&mac={ff.GetMacAddress()}");
            WebResponse resp = req.GetResponse();
            StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
            string strResponse = sr.ReadToEnd();
            if (strResponse.Equals("-2"))
            {
                this.ShowMessageAsync("","当前账号已被登录！");
            }
            else if (strResponse.Equals(""))
            {
                this.ShowMessageAsync("","账号或密码错误!");
            }else
            {
                JObject jo = (JObject)JsonConvert.DeserializeObject(strResponse);
                //this.ShowMessageAsync("", jo["userKey"].ToString());
                mw.user_Key = jo["userKey"].ToString();
                mw.user_name = jo["username"].ToString();
                mw.user_email = jo["email"].ToString();
                this.Close();
                mw.Show();
                mw.loadingScript();
            }
        }

        private void register_btn_Click(object sender, RoutedEventArgs e)
        {
            //注册按钮
                functionFactory ff = new functionFactory();
            WebRequest req = WebRequest.Create($"http://warframe.md4.cn:8081/warframeservice/warframeluaSerivce/addusr?username={reg_usr.Text}&password={ff.getMD5(reg_pwd.Password)}&email={reg_email.Text}");
            WebResponse resp = req.GetResponse();
            StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
            string strResponse = sr.ReadToEnd();
            if (strResponse.Equals("1"))
            {
                this.ShowMessageAsync("提示", "注册成功，请登录");
            }else if (strResponse.Equals("-2"))
            {
                this.ShowMessageAsync("提示", "注册失败!");
            }else if (strResponse.Equals("-1"))
            {
                this.ShowMessageAsync("提示", "账户已存在!");
            }
        }
    }
}
